from logging import getLogger
from xml.etree import ElementTree as etree

from zope.interface import implements

from meercat.base.metadata import Metadata
from meercat.base.registry import OrderedRegistry

from meercat.harvester.sfx.interfaces import ISFXFieldSet, ISFXDefaultFieldSets
from meercat.harvester.sfx.interfaces import ISFXField



log = getLogger('meercat.harvester.sfx.fieldset')

class FieldSet(OrderedRegistry):
    implements(ISFXFieldSet)
    
    def __init__(self, tag='object', format='sfx', mustProvide=ISFXField):
        self.tag = tag
        self.format = format
        super(FieldSet,self).__init__(mustProvide)
    
    @property
    def fields(self):
        return self
    
    def render(self, source, values):
        """ Render a Metadata object for the input values """
        
        root = etree.Element(self.tag)
        
        for field, value in zip(self.fields, values):
            value = field(value)
            if value is not None and etree.iselement(value):
                root.append(value)
            elif value:
                map(root.append, value)
        log.debug('%s rendering: %s' % (str(self), unicode(etree.tostring(root, encoding='utf-8'),'utf-8'),))
        return Metadata(source=source,
                        format=unicode(self.format),
                        value=unicode(etree.tostring(root, encoding='utf-8'),
                                      'utf-8'))
        